<template>
    <div>
        <div style="margin: 10px 0">
            <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search"
                      v-model="rankName"></el-input>
            <!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-message" class="ml-5" v-model="email"></el-input>-->
            <!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-position" class="ml-5" v-model="address"></el-input>-->
            <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </div>

        <div style="margin: 10px 0">
            <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
            <el-popconfirm
                    class="ml-5"
                    confirm-button-text='确定'
                    cancel-button-text='我再想想'
                    icon="el-icon-info"
                    icon-color="red"
                    title="您确定批量删除这些数据吗？"
                    @confirm="delBatch">
                <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
            </el-popconfirm>
            <!-- <el-upload action="http://localhost:9090/rankCategory/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block">
              <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
            </el-upload>
            <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button> -->
        </div>

        <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <!--<el-table-column prop="id" label="ID" width="80" sortable></el-table-column>-->
            <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
            <el-table-column prop="rankName" label="积分分类名称" align="center"></el-table-column>
            <el-table-column prop="rankYear" label="赛事年份" align="center"></el-table-column>
            <el-table-column prop="bindType" label="计入级别类型" :formatter="bindTypeFormatter"
                             align="center"></el-table-column>
            <el-table-column prop="rankRace" :show-overflow-tooltip="true" label="包含赛事" align="center"></el-table-column>
            <el-table-column prop="rankRaceId" label="包含赛事Id" v-if="false" align="center"></el-table-column>

            <el-table-column label="操作" width="180" align="center">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                        <el-button type="text" @click="handleEdit(scope.row)"><i class="el-icon el-icon-edit"></i></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                        <el-popconfirm
                                class="ml-5"
                                confirm-button-text='确定'
                                cancel-button-text='我再想想'
                                icon="el-icon-info"
                                icon-color="red"
                                title="您确定删除吗？"
                                @confirm="del(scope.row.id)"
                        >
                            <el-button type="text" slot="reference"><i class="el-icon el-icon-delete"></i></el-button>
                        </el-popconfirm>
                    </el-tooltip>

                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[10, 30, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog title="创建排名分类" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false" center>
            <el-form class="TKform" label-width="120px" size="small" style="width: 80%; margin: 0 auto"
                     :rules="rules" :model="ruleForm" ref="rankForm">
                <el-form-item prop="bindType" label="积分分类类型">
                    <el-select v-model="ruleForm.bindType" placeholder="请选择">
                        <el-option
                                v-for="item in options"
                                :key="item.type"
                                :label="item.label"
                                :value="item.type">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="rankName" label="积分分类名称">
                    <el-input v-model="ruleForm.rankName" autocomplete="off"></el-input>
                </el-form-item>
                <template>
                    <el-form-item v-if="this.ruleForm.bindType==='1'" prop="rankYear" label="全运会年份">
                        <el-date-picker v-model="ruleForm.rankYear" value-format="yyyy" type="years"
                                        @change="queryRaces(ruleForm.rankYear)">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item v-else prop="rankYear" label="赛事所属年份">
                        <el-date-picker v-model="ruleForm.rankYear" value-format="yyyy" type="years"
                                        @change="queryRaces(ruleForm.rankYear)">
                        </el-date-picker>
                    </el-form-item>
                </template>


                <el-form-item prop="rankRace" label="包含赛事">
                    <el-select v-model="ruleForm.rankRace" multiple
                               collapse-tags placeholder="请选择">
                        <el-option
                                v-for="item in raceNames"
                                :key="item.raceId"
                                :label="item.raceName+'('+item.raceStation+')'"
                                :value="item.raceId">
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="preview(ruleForm)">预 览</el-button>
            </div>
        </el-dialog>
        <el-dialog title="预览" :visible.sync="dialogPreViewVisible" top="30px" center="true"
                   width="90%">
            <div style="margin: 10px 0">
                <el-select v-model="scoreLevel" placeholder="请选择计入级别">
                    <el-option
                            v-for="(item,index) in scoreLevels"
                            :key="index"
                            :label="item.levelName"
                            :value="item.scoreLevel">
                    </el-option>
                </el-select>
                <el-button class="ml-5" type="primary" @click="queryRecord">搜索</el-button>
                <!--                <el-button type="warning" @click="reset">重置</el-button>-->
            </div>
            <el-table :data="raceRecord">
                <el-table-column property="rank" label="排名" width="150"></el-table-column>
                <el-table-column property="name" label="姓名"></el-table-column>
                <el-table-column label="头像">
                    <template slot-scope="scope">
                        <el-image style="width: 100px; height: 100px"
                                  :src="scope.row.avatar"
                                  :preview-src-list="[scope.row.avatar]">
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column property="wtId" label="WT-ID"></el-table-column>
                <el-table-column property="unit" label="代表单位"></el-table-column>
                <el-table-column property="score" label="分数" >
                    <template slot-scope="scope">
                        <span>{{ scope.row.score.toFixed(3) }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelPublic">取 消</el-button>
                <el-button type="primary" @click="save">公 示</el-button>
            </div>
            <div style="padding: 10px 0">
                <el-pagination
                        @size-change="handleSizeChange2"
                        @current-change="handleCurrentChange2"
                        :current-page="pageNum2"
                        :page-sizes="[2, 5, 10, 20]"
                        :page-size="pageSize2"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total2">
                </el-pagination>
            </div>
        </el-dialog>
        <!--更新日志-->
        <el-dialog class="dialog" title="编辑日志" :visible.sync="dialogLogVisible" ref="updateInsertDialog"
                   :close-on-click-modal="false">
            <el-form label-width="120px" size="small" style="width: 80%; margin: 0 auto">
                <el-form-item v-if="false" prop="logId" label="更新日志id">
                    <el-input v-model="form.logId" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="logTitle" label="更新标题">
                    <el-input v-model="form.logTitle" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="author" label="作者">
                    <el-input v-model="form.author" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="logContent" label="更新内容">
                    <Editor :content="content" ref="MyEditor"></Editor>
                </el-form-item>
            </el-form>
            <div slot="footer" align="center" class="dialog-footer">
                <el-button @click="dialogLogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addLog">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Editor from '../components/Editor.vue'

    export default {
        name: "RankCategory",
        components:{Editor},
        data() {
            return {
                tableData: [],
                total: 0,
                total2: 0,
                pageNum: 1,
                pageNum2: 1,
                pageSize: 10,
                pageSize2: 10,
                rankName: "",
                form: {},
                dialogFormVisible: false,
                dialogPreViewVisible: false,
                dialogLogVisible: false,
                multipleSelection: [],
                user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
                raceNames: [],
                dialogForm: {
                    "rankYear": ""
                },
                url: "",
                options: [
                    {type: '0', label: '全国积分'},
                    {type: '1', label: '全运积分'}
                ],
                raceRecord: [],
                scoreLevel: '',
                scoreLevels: [],
                oldQuery: {},
                bindType:'',
                ruleForm: {
                    rankName: '',
                    rankYear: '',
                    rankRace: [],
                    bindType: '',
                    rankRaceId: ''
                },
                rules: {
                    rankName: [
                        {required: true, message: '请输入积分名称', trigger: 'blur'},
                    ],
                    rankYear: [
                        {required: true, message: '请选择赛事年份', trigger: 'change'}
                    ],
                    rankRace: [
                        {required: true, message: '请选择比赛', trigger: 'change'},
                    ],
                    bindType: [
                        {required: true, message: '请选择绑定计入分类', trigger: 'change'},
                    ]
                },
            }
        },
        created() {
            this.load()
        },
        methods: {
            load() {
                const data = {
                    "page": this.pageNum,
                    "pageSize": this.pageSize,
                    "rankName": this.rankName
                }
                this.request.post("/rankCategory/page", data).then(res => {
                    this.tableData = res.data.data
                    this.total = res.data.total
                })
            },
            bindTypeFormatter(row) {
                if (row.bindType === "0") {
                    return "国内"
                } else {
                    return "国际"
                }

            },
            postFormatter(row) {
                switch (row.racePost) {
                    case "0":
                        return "国际级"
                        break;
                    case "1":
                        return "国家级"
                        break;
                    case "2":
                        return "预备国家级"
                        break;
                    // case "3": return "二级"
                    //   break;
                    // case "4": return "三级"
                    //   break;
                }
            },
            cancelPublic(){
                this.dialogPreViewVisible = false;
                this.dialogFormVisible =false;
            },
            /**
             * 预览
             */
            preview(row) {
                this.$refs['rankForm'].validate((valid) => {
                    if (valid) {
                        this.dialogPreViewVisible = true
                        this.request.post("/api/getLevels", {"type": row.bindType}).then(res => {
                            if (res.code === 200) {
                                this.scoreLevels = res.data
                                this.scoreLevel = this.scoreLevels[0].scoreLevel
                                //将race_id数组拼接
                                let str = "";
                                for (let i = 0; i < this.ruleForm.rankRace.length; i++) {
                                    if (i === this.ruleForm.rankRace.length - 1) {
                                        str += this.ruleForm.rankRace[i]
                                    } else {
                                        str += this.ruleForm.rankRace[i] + ";"
                                    }
                                }
                                this.ruleForm.rankRace = str;
                                const data = {
                                    "type": this.ruleForm.bindType,
                                    "rankName": this.ruleForm.rankName,
                                    "scoreLevel": this.scoreLevel,
                                    "pageSize": this.pageSize,
                                    "page": this.pageNum,
                                    "raceId": row.rankRace
                                }
                                this.oldQuery = data
                                this.request.post("/api/preview", data).then(res => {
                                    if (res.code === 200) {
                                        this.raceRecord = res.data.data
                                        this.total2 = res.data.total
                                        this.pageNum2 = res.data.page
                                        this.pageSize2 = res.data.pageSize
                                        //还原状态
                                        this.ruleForm.rankRace = str.split(";");
                                    }
                                })
                            } else {
                                this.$message.error("查询计入级别失败,无法预览")
                            }

                        })
                    }
                })
            },
            queryRecord() {
                this.oldQuery.scoreLevel = this.scoreLevel
                this.oldQuery.page = this.pageNum2
                this.oldQuery.pageSize = this.pageSize2
                this.request.post("/api/preview", this.oldQuery).then(res => {
                    this.raceRecord = res.data.data
                    this.total2 = res.data.total
                    this.pageNum2 = res.data.page
                    this.pageSize2 = res.data.pageSize
                })
            },

            /**
             * 查询赛事
             * @param rankYear
             */
            queryRaces(rankYear) {
                if (rankYear !== null && rankYear.length > 0) {
                    const data = {
                        "rankYear": rankYear
                    }
                    this.request.post("/rankCategory/queryRaces", data).then(res => {
                        this.raceNames = res.data
                    })
                }

            },
            save() {
                this.$refs['rankForm'].validate((valid) => {
                    if (valid) {
                        //将race_id数组拼接
                        let str = "";
                        for (let i = 0; i < this.ruleForm.rankRace.length; i++) {
                            if (i === this.ruleForm.rankRace.length - 1) {
                                str += this.ruleForm.rankRace[i]
                            } else {
                                str += this.ruleForm.rankRace[i] + ";"
                            }
                        }
                        this.ruleForm.rankRace = str;

                        this.request.post("/rankCategory/save", this.ruleForm).then(res => {
                            if (res.code === 200) {
                                this.$message.success("公示成功！")
                                this.dialogFormVisible = false
                                this.dialogPreViewVisible = false
                                this.load()
                                this.addLog()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    }
                })

            },
            addLog() {
                this.dialogLogVisible = true
                const now = new Date().toString();
                this.form.logContent = this.$refs.MyEditor.editor.getText();
                this.form.status = '0'
                if(this.form.logId === undefined || this.form.logId ===''){
                    this.form.logId = this.md5.md5(now)
                }
                this.request.post("/log/save", this.form).then(res => {
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        this.dialogLogVisible = false
                        this.load()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            handleAdd() {
                this.dialogFormVisible = true
                this.form = {}
                this.raceNames = []
                this.ruleForm = {}
                this.$nextTick(() => {
                    if (this.$refs.img) {
                        this.$refs.img.clearFiles();
                    }
                    if (this.$refs.file) {
                        this.$refs.file.clearFiles();
                    }
                })
            },
            handleEdit(row) {
                let years = []
                this.ruleForm = JSON.parse(JSON.stringify(row))
                this.ruleForm.rankRace = []
                this.ruleForm.rankName = row.rankName
                this.ruleForm.bindType = row.bindType
                this.ruleForm.rankYear = years
                if (typeof (this.ruleForm.rankYear) === 'string') {
                    years.push(this.ruleForm.rankYear)
                    this.queryRaces(years)
                } else {
                    this.queryRaces(this.ruleForm.rankYear)
                }

                this.dialogFormVisible = true
                this.$nextTick(() => {
                    if (this.$refs.img) {
                        this.$refs.img.clearFiles();
                    }
                    if (this.$refs.file) {
                        this.$refs.file.clearFiles();
                    }
                })
            },
            del(id) {
                this.request.delete("/rankCategory/" + id).then(res => {
                    if (res.code === 200) {
                        this.$message.success("删除成功")
                        this.load()
                    } else {
                        this.$message.error("删除失败")
                    }
                })
            },
            handleSelectionChange(val) {
                console.log(val)
                this.multipleSelection = val
            },
            delBatch() {
                if (!this.multipleSelection.length) {
                    this.$message.error("请选择需要删除的数据")
                    return
                }
                let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
                this.request.post("/rankCategory/del/batch", ids).then(res => {
                    if (res.code === 200) {
                        this.$message.success("批量删除成功")
                        this.load()
                    } else {
                        this.$message.error("批量删除失败")
                    }
                })
            },
            reset() {
                this.rankName = ""
                this.load()
            },
            handleSizeChange(pageSize) {
                console.log(pageSize)
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                console.log(pageNum)
                this.pageNum = pageNum
                this.load()
            },
            handleSizeChange2(pageSize2) {
                // console.log(pageSize)
                this.pageSize2 = pageSize2
                this.queryRecord()
            },
            handleCurrentChange2(pageNum2) {
                // console.log(pageNum)
                this.pageNum2 = pageNum2
                this.queryRecord()
            },
            handleFileUploadSuccess(res) {
                this.form.file = res
            },
            handleImgUploadSuccess(res) {
                this.form.img = res
            },
            download(url) {
                window.open(url)
            },
            exp() {
                window.open("http://localhost:9090/rankCategory/export")
            },
            handleExcelImportSuccess() {
                this.$message.success("导入成功")
                this.load()
            }
        }

    }
</script>


<style>
    .headerBg {
        background: #eee !important;
    }

    .el-button {
        margin: 0px 6px 12px;
    }
    .el-icon {
        font-size: 16px;
    }
</style>
